using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace ConcursoCV.UI 
{
	/// <summary>
	/// Summary description for Global.
	/// </summary>
	public class Global : System.Web.HttpApplication
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		public Global()
		{
			InitializeComponent();
		}	
		
		protected void Application_Start(Object sender, EventArgs e)
		{

		}
 
		protected void Session_Start(Object sender, EventArgs e)
		{

		}

		protected void Application_BeginRequest(Object sender, EventArgs e)
		{

		}

		protected void Application_EndRequest(Object sender, EventArgs e)
		{

		}

		protected void Application_AuthenticateRequest(Object sender, EventArgs e)
		{
			// get the security cookie
			HttpCookie cookie  = Request.Cookies.Get(FormsAuthentication.FormsCookieName);

			if( cookie != null )
			{
				//we got the cookie, so decrypt the value
			    FormsAuthenticationTicket ticket  = FormsAuthentication.Decrypt(cookie.Value);
				if ( ( ticket.Expired ) || (ticket.UserData.Equals(string.Empty)) )
				{
					// the ticket has expired - force user to login
					FormsAuthentication.SignOut();
					Response.Redirect("login.aspx");					
				}
				else
				{	
					// ticket is valid, set HttpContext user value
					MemoryStream buffer = new MemoryStream( Convert.FromBase64String(ticket.UserData) );
					BinaryFormatter formatter = new BinaryFormatter();
					HttpContext.Current.User = formatter.Deserialize(buffer) as IPrincipal;
				}				
			}
		}

		protected void Application_Error(Object sender, EventArgs e)
		{

		}

		protected void Session_End(Object sender, EventArgs e)
		{

		}

		protected void Application_End(Object sender, EventArgs e)
		{

		}
			
		#region Web Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.components = new System.ComponentModel.Container();
		}
		#endregion
	}
}

